#!/usr/bin/env python
# -*- coding: utf8 -*-
#-------------------------------------------------------------------------------
# Name:        baidu 网盘帐号管理
# Purpose:
#
# Author:      iori
#
# Created:     18/03/2014
# Copyright:   (c) iori 2014
# Licence:     GPLv3
#-------------------------------------------------------------------------------

# system libs
import logging
from cStringIO import StringIO

# third part libs
from PIL import Image
import requests
from pyquery import PyQuery

# user libs
import const
from utils import get_session

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

class Baidu(object):
    def __init__(self, name, pwd, sn=None):
        self.sn = get_session()
        self.name = name
        self.pwd = pwd
        self.login()

    def login(self):
        ''' 通过手机方式来登陆baidu， 比较容易 '''
        self.sn.headers['Referer'] = 'http://wappass.baidu.com/'
        res = self.sn.get('http://wappass.baidu.com/passport/login')
        while True:
            bd = PyQuery(res.content)
            vcodestr = bd('input[name=vcodestr]').eq(0).attr.value
            if vcodestr:
                content =self.sn.get('http://wappass.baidu.com/cgi-bin/genimage?{}'.format(vcodestr)).content
                img = Image.open(StringIO(content))
                img.show()
                verifycode = raw_input('enter verify image: ')
            else:
                verifycode = ''
            data={'bd_page_type': '',
                'bdcm': bd('input[name=bdcm]').eq(0).attr.value,
                'from': '',
                'isphone': '0',
                'loginmerge': '1',
                'password': self.pwd,
                'pu': '',
                'quick_user': '0',
                'skin': 'default_v2',
                'sp_login': 'waprate',
                'ssid': '',
                'submit': u'登录',
                'tn': '',
                'tpl': '',
                'type': '',
                'u': bd('input[name=u]').eq(0).attr.value,
                'uid': bd('input[name=uid]').eq(0).attr.value,
                'uname_login': '',
                'username': self.name,
                'vcodestr': vcodestr,
                'verifycode': verifycode}
            res = self.sn.post('http://wappass.baidu.com/passport/login', data=data, stream=True,allow_redirects=False)
            if res.status_code > 300: # meaning ok
                logger.info('{} login success'.format(self.name))
                return
            # 直接用: u'密码有误' in res.text 得不到正确的结果
            body = res.content.decode('utf8')
            if u'验证码' in body:
                logger.info(u'验证码错误')
                continue
            else:
                if u'密码有误' in body:
                    logger.error('password wrong')
                return



def main():
    Baidu('wucai0503', '86612082')
    pass

if __name__ == '__main__':
    main()
